const formidable = require('formidable');
const fs = require('fs'),
    domain = "http://localhost:8089",
    AVATAR_UPLOAD_FOLDER = '/img/';
class UploadFiles {
    constructor(data) {
        this.data = data;
    }
    async imgSave() {
        const form = new formidable.IncomingForm(); //创建上传表单
        form.encoding = 'utf-8'; //设置编辑
        form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
        //form.uploadDir = 'C:/Users/qinga/Desktop/sb/farm_manage/public/img'; //设置上传目录
        form.keepExtensions = true; //保留后缀
        form.maxFieldsSize = 4 * 1024 * 1024; //文件大小
        return new Promise((resolve,reject)=>{
            form.parse(this.data,(err, fields, files) => {
                if (err) {
                    res.locals.error = err;
                    reject({
                        status: 4,
                        msg: '上传失败',
                        data: []
                    }) ;
                }
                var extName = ''; //后缀名
                switch (files.file.type) {
                    case 'image/jpg':
                        extName = 'jpg';
                        break;
                    case 'image/jpeg':
                        extName = 'jpg';
                        break;
                    case 'image/png':
                        extName = 'png';
                        break;
                    case 'image/x-png':
                        extName = 'png';
                        break;
                }
                if (extName == null) {
                    res.locals.error = '只支持png和jpg格式图片';
                    reject('图片格式错误');
                }
                var avatarName = Math.random() + '.' + extName;
                var newPath = form.uploadDir + avatarName;  //图片写入地址；
                var showUrl = domain + AVATAR_UPLOAD_FOLDER + avatarName;  //显示地址；
                fs.renameSync(files.file.path, newPath); //重命名
                resolve(showUrl);
            });
        }) 
       
    }
}

module.exports = {UploadFiles};